using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NTTHAO.CommonWeb;
using NTTHAO.Web.BL.CommonPage;
using NTTHAO.Imaging;
using System.IO;

public partial class admin_webparts_Plug_ins_CommonPage_CommonAlbumInput : System.Web.UI.UserControl
{
    public string _ErrorMessage = String.Empty;
    public CommonAlbum _Album = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        this.btnSave2.Text = this.btnSave.Text = LanguageUtility.GetLanguageText("SAVE", Session);
        this.chkActive.Text = LanguageUtility.GetLanguageText("ACTIVE", Session);
        this.txtResizeImageWidth.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtResizeImageHeight.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtResizeMiniImageWidth.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtResizeMiniImageHeight.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtDefaultWidth.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtDefaultHeight.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtDefaultMiniWidth.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtDefaultMiniHeight.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtImagePath.InnerHtml = "./" + Constant.UPLOAD_FILE_PATH + "albums/&lt;Album ID&gt;/";

        string adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default_admin.css";
        if (!System.IO.File.Exists(Server.MapPath(adminCss)))
        {
            adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default.css";
        }
        this._ContentCKEditor.ContentsCss = adminCss;
        this._ContentCKEditor.Entities = false;
        //this._ContentCKEditor.ForcePasteAsPlainText = true;

        if (!IsPostBack)
        {
            txtInsertDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDefaultWidth.Text = ConfigValues.GetConfigValue("ALBUM_IMAGE_WIDTH_DEFAULT");
            this.txtDefaultHeight.Text = ConfigValues.GetConfigValue("ALBUM_IMAGE_HEIGHT_DEFAULT");
            this.txtDefaultMiniWidth.Text = ConfigValues.GetConfigValue("ALBUM_MINI_IMAGE_WIDTH_DEFAULT");
            this.txtDefaultMiniHeight.Text = ConfigValues.GetConfigValue("ALBUM_MINI_IMAGE_HEIGHT_DEFAULT");

            this.txtResizeMiniImageWidth.Text = ConfigValues.GetConfigValue("ALBUM_MINI_IMAGE_WIDTH_RESIZE");
            this.txtResizeMiniImageHeight.Text = ConfigValues.GetConfigValue("ALBUM_MINI_IMAGE_HEIGHT_RESIZE");
            this.txtResizeImageWidth.Text = ConfigValues.GetConfigValue("ALBUM_IMAGE_WIDTH_RESIZE");
            this.txtResizeImageHeight.Text = ConfigValues.GetConfigValue("ALBUM_IMAGE_HEIGHT_RESIZE");

            //chkResizeImage.Checked = chkResizeMiniImage.Checked = false;

            for (int i = 0; i < 24; i++)
            {
                cmbInsertHour.Items.Add(new ListItem(i.ToString("00"), i.ToString("00")));
            }
            for (int i = 0; i < 60; i++)
            {
                cmbInsertMin.Items.Add(new ListItem(i.ToString("00"), i.ToString("00")));
            }
            this.cmbInsertHour.Text = DateTime.Now.Hour.ToString("00");
            this.cmbInsertMin.Text = DateTime.Now.Minute.ToString("00");

            if (Request.QueryString["id"] != null)
            {
                try
                {
                    if (!"editalbum".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
                    {
                        throw new Exception();
                    }
                    CommonAlbum album = new CommonAlbum(Int32.Parse(Request.QueryString["id"].Trim()));
                    if (album.ID < 1)
                    {
                        throw new Exception();
                    }
                    this.txtAlbumName.Text = album.AlbumName;
                    this.txtDescription.Text = album.Description;
                    this._ContentCKEditor.Text = album.Content;
                    this.txtDefaultWidth.Text = album.DefaultWidth.ToString();
                    this.txtDefaultHeight.Text = album.DefaultHeight.ToString();
                    this.txtDefaultMiniWidth.Text = album.MiniDefaultWidth.ToString();
                    this.txtDefaultMiniHeight.Text = album.MiniDefaultHeight.ToString();
                    this.txtImagePath.InnerHtml = album.ImagePath;
                    this.chkActive.Checked = album.Active;
                    this.txtInsertDate.Text = album.InsertDate.ToString("dd/MM/yyyy");
                    this.cmbInsertHour.Text = album.InsertDate.Hour.ToString("00");
                    this.cmbInsertMin.Text = album.InsertDate.Minute.ToString("00");

                    this.txtDefaultWidth.Enabled
                        = this.txtDefaultHeight.Enabled
                        = this.txtDefaultMiniWidth.Enabled
                        = this.txtDefaultMiniHeight.Enabled
                        = false;

                    this._Album = album;
                    //this.txtAlbumName.Enabled = false;
                }
                catch (Exception)
                {
                    Response.Redirect("CommonPageContent.aspx?action=invalidurl", false);
                    return;
                }
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            CommonAlbum album = null;

            if ("editalbum".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
            {
                album = new CommonAlbum(Int32.Parse(Request.QueryString["id"].Trim()));
            }
            else
            {
                album = new CommonAlbum();
                album.MenuID = Int32.Parse(Request.QueryString["mnuid"].Trim());
                album.Image = "";
                album.MiniImage = "";
            }

            album.AlbumName = txtAlbumName.Text;
            album.Description = txtDescription.Text;
            album.Content = _ContentCKEditor.Text;
            album.DefaultWidth = Int32.Parse(txtDefaultWidth.Text.Trim());
            album.DefaultHeight = Int32.Parse(txtDefaultHeight.Text.Trim());
            album.MiniDefaultWidth = Int32.Parse(txtDefaultMiniWidth.Text.Trim());
            album.MiniDefaultHeight = Int32.Parse(txtDefaultMiniHeight.Text.Trim());
            album.Active = chkActive.Checked;
            try
            {
                string[] dSpl = txtInsertDate.Text.Trim().Split(new string[] { "/" }, StringSplitOptions.None);
                int hour = 0;
                int minute = 0;
                Int32.TryParse(cmbInsertHour.SelectedValue.Trim(), out hour);
                Int32.TryParse(cmbInsertMin.SelectedValue.Trim(), out minute);
                album.InsertDate = new DateTime(Convert.ToInt32(dSpl[2]), Convert.ToInt32(dSpl[1]), Convert.ToInt32(dSpl[0]), hour, minute, 0);
            }
            catch { }

            string uploadedFileName = String.Empty;
            string miniFileName = String.Empty;
            string filePath = "../" + Constant.UPLOAD_FILE_PATH + "albums/";
            if (!Directory.Exists(Server.MapPath(filePath)))
            {
                Directory.CreateDirectory(Server.MapPath(filePath));
            }
            if (this.fuPresentativeImage.HasFile)
            {
                if (this.fuPresentativeImage.PostedFile.FileName.Contains("."))
                {
                    uploadedFileName = "Pre_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(this.fuPresentativeImage.PostedFile.FileName);

                    this.fuPresentativeImage.PostedFile.SaveAs(Server.MapPath(filePath + uploadedFileName));
                }
            }
            if (this.fuMiniImage.HasFile)
            {
                if (this.fuMiniImage.PostedFile.FileName.Contains("."))
                {
                    miniFileName = "Mini_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(this.fuMiniImage.PostedFile.FileName);

                    this.fuMiniImage.PostedFile.SaveAs(Server.MapPath(filePath + miniFileName));
                }
            }

            if ("editalbum".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
            {
                if (uploadedFileName != string.Empty)
                {
                    if (System.IO.File.Exists(Server.MapPath("../" + album.ImagePath + "/" + album.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("../" + album.ImagePath + "/" + album.Image));
                    }
                    if (System.IO.File.Exists(Server.MapPath("../" + album.ImagePath + "/Mini_" + album.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath("../" + album.ImagePath + "/Mini_" + album.Image));
                    }
                    album.Image = "";
                }

                if (miniFileName != string.Empty || chkRemoveMiniImage.Checked)
                {
                    if (System.IO.File.Exists(Server.MapPath("../" + album.ImagePath + "/" + album.MiniImage)))
                    {
                        System.IO.File.Delete(Server.MapPath("../" + album.ImagePath + "/" + album.MiniImage));
                    }
                    album.MiniImage = "";
                }
            }
            else
            {
                album.ImagePath = Constant.UPLOAD_FILE_PATH + "albums/";
                album.Insert();
                album.ImagePath = Constant.UPLOAD_FILE_PATH + "albums/" + album.ID.ToString() + "/";
                album.Update();
            }

            {
                if (!Directory.Exists(Server.MapPath(filePath + album.ID.ToString() + "/")))
                {
                    Directory.CreateDirectory(Server.MapPath(filePath + album.ID.ToString() + "/"));
                }
                try
                {
                    if (uploadedFileName != string.Empty)
                    {
                        album.Image = album.URLName + "-" + album.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + System.IO.Path.GetExtension(uploadedFileName);
                        string serverFilePath = Server.MapPath(filePath + album.ID.ToString() + "/" + album.Image);
                        if (File.Exists(serverFilePath))
                        {
                            File.Delete(serverFilePath);
                        }
                        File.Move(Server.MapPath(filePath + uploadedFileName), serverFilePath);

                        if (chkResizeImage.Checked || Constant.ADD_LAYER_MASK)
                        {
                            album.Image = System.IO.Path.GetFileName(ImageUtilities.CompressImageToJpeg(serverFilePath, ImageUtilities.HIGHT_PROGRESSIVE));
                            serverFilePath = Path.ChangeExtension(serverFilePath, Path.GetExtension(album.Image));
                        }

                        if (chkResizeImage.Checked)
                        {
                            int width = int.MaxValue, height = int.MaxValue;
                            width = Int32.TryParse(txtResizeImageWidth.Text.Trim(), out width) ? width : 10000;
                            height = Int32.TryParse(txtResizeImageHeight.Text.Trim(), out height) ? height : 10000;
                            if (width > 0 && height > 0)
                            {
                                string resizedImagePath = ImageUtilities.ResizeImageToJpeg(serverFilePath, width, height, ResizeOptions.MaximumSizeFix, System.Drawing.Color.White, ImageUtilities.HIGHT_PROGRESSIVE);
                                album.Image = Path.GetFileName(resizedImagePath);
                            }
                        }

                        //layer mask
                        if (Constant.ADD_LAYER_MASK)
                        {
                            float left = 0, top = 0, width = 0, height = 0, opacity = 1;
                            float.TryParse(ConfigValues.GetConfigValue("MASK_TOP_PERCENT").Trim(), out top);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_LEFT_PERCENT").Trim(), out left);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_WIDTH_PERCENT").Trim(), out width);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_HEIGHT_PERCENT").Trim(), out height);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_OPACITY").Trim(), out opacity);

                            ImageUtilities.DrawLayerMask(Path.ChangeExtension(serverFilePath, Path.GetExtension(album.Image)), Server.MapPath("../" + Constant.MASK_IMAGE_FILE), top, left, width, height, ResizeOptions.MaximumSizeFix, opacity, ImageUtilities.HIGHT_PROGRESSIVE);
                        }
                        // end

                        //string miniFilePath = Server.MapPath(filePath + album.ID.ToString() + "/" + "Mini_" + album.Image);
                        //if (File.Exists(miniFilePath))
                        //{
                        //    File.Delete(miniFilePath);
                        //}

                        //File.Copy(serverFilePath, miniFilePath);
                        //ImageUtilities.MaximumSizeFit(miniFilePath, album.MiniDefaultWidth, album.MiniDefaultHeight, ImageUtilities.HIGHT_PROGRESSIVE);
                        ////Common.ResizeImage(miniFilePath, album.MiniDefaultWidth, album.MiniDefaultHeight);

                        ////layer mask
                        //if (Constant.ADD_LAYER_MASK)
                        //{
                        //    float left = 0, top = 0, width = 0, height = 0, opacity = 1;
                        //    float.TryParse(ConfigValues.GetConfigValue("MASK_TOP_PERCENT").Trim(), out top);
                        //    float.TryParse(ConfigValues.GetConfigValue("MASK_LEFT_PERCENT").Trim(), out left);
                        //    float.TryParse(ConfigValues.GetConfigValue("MASK_WIDTH_PERCENT").Trim(), out width);
                        //    float.TryParse(ConfigValues.GetConfigValue("MASK_HEIGHT_PERCENT").Trim(), out height);
                        //    float.TryParse(ConfigValues.GetConfigValue("MASK_OPACITY").Trim(), out opacity);

                        //    ImageUtilities.DrawLayerMask(miniFilePath, Server.MapPath("../" + Constant.MASK_IMAGE_FILE), top, left, width, height, ResizeOptions.MaximumSizeFix, opacity, ImageUtilities.HIGHT_PROGRESSIVE);
                        //}
                        //// end
                    }
                }
                catch { }
                try
                {
                    if (miniFileName != string.Empty)
                    {
                        album.MiniImage = album.URLName + "-" + "Mini_" + album.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + System.IO.Path.GetExtension(miniFileName);
                        string serverFilePath = Server.MapPath(filePath + album.ID.ToString() + "/" + album.MiniImage);
                        if (File.Exists(serverFilePath))
                        {
                            File.Delete(serverFilePath);
                        }
                        File.Move(Server.MapPath(filePath + miniFileName), serverFilePath);

                        if (chkResizeMiniImage.Checked || Constant.ADD_LAYER_MASK)
                        {
                            serverFilePath = ImageUtilities.CompressImageToJpeg(serverFilePath, ImageUtilities.HIGHT_PROGRESSIVE);
                            album.MiniImage = System.IO.Path.GetFileName(serverFilePath);
                        }

                        if (chkResizeMiniImage.Checked)
                        {
                            int width = int.MaxValue, height = int.MaxValue;
                            width = Int32.TryParse(txtResizeImageWidth.Text.Trim(), out width) ? width : 10000;
                            height = Int32.TryParse(txtResizeImageHeight.Text.Trim(), out height) ? height : 10000;
                            if (width > 0 && height > 0)
                            {
                                string resizedImagePath = ImageUtilities.ResizeImageToJpeg(serverFilePath, width, height, ResizeOptions.MaximumSizeFix, System.Drawing.Color.White, ImageUtilities.HIGHT_PROGRESSIVE);
                                album.MiniImage = Path.GetFileName(resizedImagePath);
                            }
                        }

                        //layer mask
                        if (Constant.ADD_LAYER_MASK)
                        {
                            float left = 0, top = 0, width = 0, height = 0, opacity = 1;
                            float.TryParse(ConfigValues.GetConfigValue("MASK_TOP_PERCENT").Trim(), out top);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_LEFT_PERCENT").Trim(), out left);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_WIDTH_PERCENT").Trim(), out width);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_HEIGHT_PERCENT").Trim(), out height);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_OPACITY").Trim(), out opacity);

                            ImageUtilities.DrawLayerMask(Path.ChangeExtension(serverFilePath, Path.GetExtension(album.MiniImage)), Server.MapPath("../" + Constant.MASK_IMAGE_FILE), top, left, width, height, ResizeOptions.MaximumSizeFix, opacity, ImageUtilities.HIGHT_PROGRESSIVE);
                        }
                        // end
                    }
                }
                catch { }

                album.Update();
            }

            Response.Redirect("CommonPageContent.aspx?action=viewalbum&g=" + Request.QueryString["g"] + "&mnuid=" + Request.QueryString["mnuid"] + "&id=" + album.ID.ToString() + "&time=" + DateTime.Now.Ticks.ToString(), false);
        }
        catch (Exception ex)
        {
            if (ex != null)
            {
                this._ErrorMessage = ex.Message;
                if (ex.StackTrace != null)
                {
                    this._ErrorMessage += "--" + ex.StackTrace;
                }
            }
            else
            {
                this._ErrorMessage = "Unknown error.";
            }
        }
    }
}
